package com.jiguang.shangcheng.servlet;

import com.jiguang.shangcheng.dao.AdminDao;
import com.jiguang.shangcheng.dao.ShangChengDao;
import com.jiguang.shangcheng.pojo.User;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/shang/login")
public class login extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("UTF-8");

        //获取参数
        String number = req.getParameter("number");
        String pwd = req.getParameter("pwd");

        //判断账号密码是否正确
        ShangChengDao shangChengDao = new ShangChengDao();
        boolean result = shangChengDao.login(number, pwd);

        if(result){
            //登录成功
            HttpSession session = req.getSession();
            //查询用户信息
            User user = shangChengDao.selectUser(number,pwd);
            //判断账号是否正常
            if(!user.getState().equals("0")){
                PrintWriter out = resp.getWriter();
                switch (user.getState()){
                    case "1":
                        out.println("<script>alert('登录失败,账号被封，请联系管理员');location.href='/shang/login.jsp';</script>");
                        break;
                    case "2":
                        out.println("<script>alert('登录失败,账号已注销，请联系管理员');location.href='/shang/login.jsp';</script>");
                        break;
                    case "3":
                        out.println("<script>alert('登录失败,请等待管理员通过注册');location.href='/shang/login.jsp';</script>");
                        break;
                }
                out.close();
                return;
            }
            //放入session
            session.setAttribute("name",user);
            //isLogin：1是普通用户登录，2是管理员登录
            session.setAttribute("isLogin","1");

            //返回后台首页
            resp.sendRedirect("/shang/shang_index");
        }else{
            //登录失败
            PrintWriter out = resp.getWriter();
            out.println("<script>alert('登录失败,账号或密码错误');location.href='/shang/login.jsp';</script>");
            out.close();
        }
    }
}
